import Message from "../../../miniprogram_npm/tdesign-miniprogram/message/index";
import { UaIpEntity } from "../../../models/ua-ip.model";
import { TradeInfoType, TradeInfoTypeList, TradeInfoTypeMap, TradeType, TradeTypeList, TradeTypeMap, UaTradeEntity } from "../../../models/ua-trade.model";
import { UaUserDeckEntity } from "../../../models/ua-user-deck.model";
import { GlobalService } from "../../../services/global.service";
import { LocalStorage } from "../../../services/local-storage.service";
import { UaIpService } from "../../../services/ua-ip.service";
import { UaTradeService } from "../../../services/ua-trade.service";

// pages/user/user-trade-edit/user-trade-edit.page.ts
Page({

  /**
   * 页面的初始数据
   */
  data: {
    logo: "",
    description: '',
    link: '',
    price: 0,
    priceError: false,
    ipText: '全部作品',
    ipList: [{ label: "全部作品", value: 0 }],
    ipVisible: false,
    ip: 0,
    tradeTypeText: '出售',
    tradeTypeList: TradeTypeList,
    tradeTypeVisible: false,
    tradeType: TradeType.SELL,
    tradeInfoTypeText: '大套',
    tradeInfoTypeList: TradeInfoTypeList,
    tradeInfoTypeVisible: false,
    tradeInfoType: TradeInfoType.SUIT,
    removeable: false,
  },

  customData: {
    tradeId: undefined as number | undefined,
    authorId: undefined as number | undefined,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options: any) {
    GlobalService.clearCurrentEditingDeckInfo();
    this.customData.tradeId = options.tradeId;
    if (options.tradeId) {
      wx.setNavigationBarTitle({
        title: '编辑集换信息'
      });
    } else {
      wx.setNavigationBarTitle({
        title: '创建集换信息'
      });
    }
    UaIpService.fetchUaIpList().then((response: UaIpEntity[]) => {
      const ipList: { label: string, value: number }[] = [{ label: "全部作品", value: 0 }];
      const ipLogoMap: { [key: number]: string } = {};
      for (const ip of response) {
        ipList.push({
          label: ip.ipTitle!,
          value: ip.id!
        });
        ipLogoMap[ip.id!] = ip.ipTitleLogo!;
      }
      this.setData({
        ipList,
        ipLogoMap,
        removeable: !!this.customData.tradeId
      });
      this.customData.authorId = LocalStorage.getUserInfo()?.id;
      if (this.customData.tradeId) {
        this.initTradeInfo();
      }
    });
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() { },

  initTradeInfo() {
    UaTradeService.findById(this.customData.tradeId!).then((response: UaTradeEntity) => {
      if (response) {
        console.log(response);
        this.customData.authorId = response.userId;
        let ipText = '全部作品';
        if (!!response.ipId) {
          for (const ip of this.data.ipList) {
            if (ip.value === response.ipId) {
              ipText = ip.label;
            }
          }
        }
        this.setData({
          description: response.description,
          price: response.price,
          priceError: false,
          ip: response.ipId,
          link: response.link,
          ipText,
          tradeInfoType: response.tradeInfoType,
          tradeInfoTypeText: TradeInfoTypeMap[response.tradeInfoType!],
          tradeType: response.tradeType,
          tradeTypeText: TradeTypeMap[response.tradeType!],
        })
      }
    })
  },

  submit() {
    if (this.customData.tradeId && LocalStorage.getUserInfo()?.id === this.customData.authorId) {
      this.update();
    } else {
      this.create();
    }
  },

  create() {
    UaTradeService.createTrade({
      userId: this.customData.authorId,
      ipId: this.data.ip,
      description: this.data.description,
      price: this.data.price,
      tradeType: this.data.tradeType,
      tradeInfoType: this.data.tradeInfoType,
      link: this.data.link
    }).then((response: UaUserDeckEntity) => {
      if (response) {
        Message.success({
          context: this,
          offset: [20, 32],
          duration: 3000,
          content: `创建成功`,
        });
        wx.navigateBack({ delta: 1 })
      }
    })
  },

  update() {
    UaTradeService.updateTrade({
      id: this.customData.tradeId,
      ipId: this.data.ip,
      userId: this.customData.authorId,
      description: this.data.description,
      price: this.data.price,
      tradeType: this.data.tradeType,
      tradeInfoType: this.data.tradeInfoType,
      link: this.data.link
    }).then((response: UaUserDeckEntity) => {
      if (response) {
        Message.success({
          context: this,
          offset: [20, 32],
          duration: 3000,
          content: `保存成功`,
        });
        setTimeout(() => {
          wx.navigateBack();
        }, 1000);
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  descriptionChange(e: any) {
    this.setData({
      description: e.detail.value
    });
  },

  linkChange(e: any) {
    this.setData({
      link: e.detail.value
    });
  },

  onDelete(e: any) {
    wx.showModal({
      title: '是否删除？',
      confirmText: "删除",
      cancelText: "取消",
      showCancel: true,
      confirmColor: "#eb445a",
      success: (res) => {
        if (res.confirm) {
          UaTradeService.removeById(this.customData.tradeId!).then(() => {
            Message.success({
              context: this,
              offset: [20, 32],
              duration: 3000,
              content: `保存成功`,
            });
            setTimeout(() => {
              wx.navigateBack();
            }, 1000);
          })
        }
      }
    });
  },

  save() {
    if (!this.data.description) {
      Message.error({
        context: this,
        offset: [20, 32],
        duration: 3000,
        content: `请填写商品描述`,
      });
      return;
    }
    if (!!this.data.priceError || !this.data.price) {
      Message.error({
        context: this,
        offset: [20, 32],
        duration: 3000,
        content: `请填写正确的价格`,
      });
      return;
    }
    if (!LocalStorage.getUserInfo()?.nickName) {
      this.editUserInfo({});
      return;
    }
    this.submit();
  },

  editUserInfo(e: any) {
    wx.showModal({
      title: '添加集换信息前需要先完善个人信息',
      confirmText: "确定",
      cancelText: "取消",
      showCancel: true,
      content: this.data.description,
      success: () => {
        wx.navigateTo({
          url: '/pages/user/user-info-edit/user-info-edit.page',
        });
      }
    });
  },

  onIpPicker() {
    this.setData({
      ipVisible: true
    });
  },

  onIpPickerCancel() {
    this.setData({
      ipVisible: false
    });
  },

  onIpPickerConfirm(e: any) {
    this.setData({
      ipText: e.detail.label[0],
      ip: e.detail.value[0]
    });
  },

  onTradeTypePicker() {
    this.setData({
      tradeTypeVisible: true
    });
  },

  onTradeTypePickerCancel() {
    this.setData({
      tradeTypeVisible: false
    });
  },

  onTradeTypePickerConfirm(e: any) {
    this.setData({
      tradeTypeText: e.detail.label[0],
      tradeType: e.detail.value[0]
    });
  },

  onTradeInfoTypePicker() {
    this.setData({
      tradeInfoTypeVisible: true
    });
  },

  onTradeInfoTypePickerCancel() {
    this.setData({
      tradeInfoTypeVisible: false
    });
  },

  onTradeInfoTypePickerConfirm(e: any) {
    this.setData({
      tradeInfoTypeText: e.detail.label[0],
      tradeInfoType: e.detail.value[0]
    });
  },

  onPriceInput(e: any) {
    const isNumber = /^\d+(\.\d+)?$/.test(e.detail.value);
    this.setData({
      priceError: !isNumber,
      price: e.detail.value
    });
  },

})